﻿define('validation', ['loc'], function () {
    ko.validation.init({
        insertMessages: false,
        decorateElement: true
    });
    
    ko.bindingHandlers.validationPopover = {
        init: function(element) {
            var el = $(element);
            el.tooltip({
                content: function () {
                    return $(this).attr('title');
                },
                tooltipClass: 'error-tooltip ui-corner-all',
                position: {
                    my: "center bottom-20",
                    at: "center top",
                    using: function (position, feedback) {
                        $(this).css(position);
                        $("<div>")
                        .addClass("arrow")
                        .addClass(feedback.vertical)
                        .addClass(feedback.horizontal)
                        .appendTo(this);
                    }
                }
            });
            
            ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
                $(element).tooltip('destroy');
            });
        },
        update: function (element, valueAccessor) {
            var obsv = valueAccessor(),
                el = $(element),
                val = ko.utils.unwrapObservable(obsv), //important
                controlGroup = el.closest('.control-group'),
                isModified = false,
                isValid = false;

            obsv.extend({ validatable: true });
            isModified = obsv.isModified();
            isValid = obsv.isValid();

            if (!isValid && isModified) {
                controlGroup.addClass('error');
            } else {
                controlGroup.removeClass('error');
            }

            var visiblityAccessor = function () {
                return isModified ? !isValid : false;
            };
            
            ko.bindingHandlers.attr.update(element, function() { return { 'title': obsv.error }; });
            ko.bindingHandlers.visible.update(element, visiblityAccessor);
        }
    };

    ko.validation.rules['equalTo'] = {
        validator: function(val, params) {
            return val === params.model[params.prop]();
        },
        message: 'Field value is invalid'
    };

    ko.validation.registerExtenders();

});